﻿using System;
using System.Diagnostics;
using IntegrationTests.Core.Websites;
using TechTalk.SpecFlow;

namespace IntegrationTests
{
	[Binding]
	public class EventDefinitions
	{
		private static Process process;

		public EventDefinitions()
		{
			
		}

		[BeforeStep]
		public void BeforeStep()
		{
		}

		[AfterStep]
		public void AfterStep()
		{
		}

		[BeforeScenarioBlock]
		public void BeforeScenarioBlock()
		{
		}


		public void AfterScenarioBlock()
		{
		}

		[BeforeScenario]
		public void BeforeScenario()
		{
		}

		[AfterScenario("ExpectedBug")]
		public void AfterScenario()
		{
			if (ScenarioContext.Current.TestError != null)
				Console.WriteLine("Тест должен падать.");

			AfterScenarioAlways();
		}

		[AfterScenario]
		public void AfterScenarioAlways()
		{
			WebsiteFactory.StopCurrentWebsite();
		}

		[BeforeFeature]
		public static void BeforeFeature()
		{
		}

		[AfterFeature]
		public static void AfterFeature()
		{
		}

		[BeforeScenario, BeforeTestRun]
		public static void StartSeleniumServer()
		{
			if (ProcessRunned())
				return;

			var startInfo = new ProcessStartInfo
			                	{
			                		FileName = @"java",
									Arguments = @"-jar -Xms32m -Xmx256m D:\Configuration\selenium-server-standalone-2.0b1.jar -port 9001",
			                		WorkingDirectory = @"c:\temp\",
			                		UseShellExecute = false,
                                    RedirectStandardOutput = true,
                                    RedirectStandardInput = true,
                                    RedirectStandardError = true,
			                	};
			//startInfo.EnvironmentVariables["TMP"] = @"c:\temp\";
			//startInfo.EnvironmentVariables["TEMP"] = @"c:\temp\";

			process = new Process
			          	{
			          		StartInfo = startInfo,
			          	};
			process.Start();
			process.BeginErrorReadLine();
			process.BeginOutputReadLine();
		}

		[AfterTestRun]
		public static void KillSeleniumServer()
		{
			if (ProcessRunned())
			{
				process.Kill();
			}
		}

		private static bool ProcessRunned()
		{
			try
			{
				return process.HasExited == false;
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
}